<template>
  <div id="Xiang">
    <Swipar :imgheight="25.5088" :item="lubo" />
    <div class="back-icon">
      <van-icon color="#fff" name="arrow-left" @click="router.go(-1)" />
    </div>
    <Tixing :item="item" />
    <Moreshop />
    <goodinfo :item="item" />
    <gooddetail :item="item" />
    <h3 style="text-align: center">更多产品</h3>
    <div class="tui">
      <div id="list_item" v-for="item in randomList" :key="item._id" @click="router.push(`/xiang?_id=${item._id}`)">
        <div id="item_img">
          <img :src="item.img" alt="" style="width:100%;height:100%">
        </div>
        <div id="item_con">
          <div class="ctitle">{{ item.name }}&nbsp;&nbsp;100g/包</div>
          <div class="cnew">好货上新</div>
          <div class="cbtn">
            <button style="background:rgb(239, 128, 130);color:white;border:none;">已省{{ item.original - item.price
              }}元</button>
            <button style="border:1px solid red;background:white">限购十份</button>
          </div>
          <div class="cfot">
            <div class="cfot_left">
              <span style="color:red;">￥{{ item.price }}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <span class="del">{{ item.original }}</span>
            </div>
            <div class="cfot_right">
              <div class="join">加入购物车</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <van-sticky position="bottom">
      <van-action-bar>
        <van-action-bar-icon icon="chat-o" text="客服" @click="router.push('/chat')" />
        <van-action-bar-icon icon="shop-o" text="首页" @click="router.push('/home')" />
        <van-action-bar-icon icon="cart-o" text="购物车" :badge='totalSelectedCount' />
        <van-action-bar-button type="warning" text="加入购物车" @click="addShop(item)" />
        <van-action-bar-button type="danger" text="立即购买" @click="onGou" />
      </van-action-bar>
    </van-sticky>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import axios from 'axios';
import { useRoute } from 'vue-router';
import { useRouter } from 'vue-router';
const router = useRouter()
// 导入轮播图组件
import Swipar from "@/components/Swaper.vue"
import Tixing from './components/Tixing.vue';
import Moreshop from './components/More.vue'
import goodinfo from './components/GoodInfo.vue'
import gooddetail from './components/GoodDetail.vue'

const item = ref({});
const route = useRoute()
const _id = ref('')
const lubo = ref([])
const getXiang = async () => {
  const { data } = await axios.get('http://localhost:3000/xiang', {
    params: { _id: _id.value }
  })
  item.value = data.xiang;
  lubo.value = item.value.img
  
}
onMounted(() => {
  if (route.query._id) {
    _id.value = route.query._id as string;
    // console.log(_id.value);
    getXiang();
  }
});
// 随机展示四条数据
const randomList = ref([]);
const list1 = ref([])
const shop = ref([])
const getShop = async () => {
  const { data } = await axios.get('http://localhost:3000/shop')
  shop.value = data.shop
}
const getList = async () => {
  let { data } = await axios.get('http://localhost:3000/list');
  list1.value = data.list
}
onMounted(() => {
  getList()
  getShop()
})
const selectRandomItems = () => {
  // 生成随机索引并获取两个随机项
  const indices = new Set<number>();
  while (indices.size < 2 && indices.size < list1.value.length) {
    indices.add(Math.floor(Math.random() * list1.value.length));
  }
  randomList.value = Array.from(indices).map(index => list1.value[index]);
};
watch(list1, () => {
  if (list1.value.length > randomList.value.length || list1.value.length < randomList.value.length) {
    selectRandomItems();
  }
});
const addShop = async (product: any) => {
  try {
    // 检查购物车中是否已存在该商品
    const { data: shopData } = await axios.get('http://localhost:3000/shop');
    const existingProduct = shopData.shop.find((item: any) => item._id === product._id);
    if (existingProduct) {
      // 如果存在，更新数量
      await axios.put('http://localhost:3000/updshop', {
        _id: existingProduct._id,
        num: existingProduct.num + 1,
      });
    } else {
      // 如果不存在，添加新商品，初始数量为 1
      await axios.post('http://localhost:3000/addshop', {
        ...product,
        num: 1,
      });
    }
    getShop()
  } catch (error) {
    console.error('添加到购物车失败：', error);
  }
};
//   跳转到购物车
const onGou = () => {
  router.push('/cart');
}
// 对去下单总数进行计算
const totalSelectedCount = computed(() => {
  console.log(shop.value);
  return shop.value.reduce((total, item) => total + item.num, 0);
});

</script>

<style scoped lang="less">
#Xiang {
  height: 100vh;
  background: #f7f7f7;
  position: relative;

  .back-icon {
    background-color: #797979;
    padding: .2834rem;
    position: absolute;
    top: 1.1337rem;
    left: .5669rem;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .bottom {
    display: flex;
    justify-content: space-around;
    background-color: #fff;
    padding: .5rem 1rem 1rem;

    .go-home {
      display: flex;
      flex-direction: column;
      font-size: .7936rem;
      justify-content: center;
      align-items: center;
    }

    .go-car {
      display: flex;
      flex-direction: column;
      font-size: .7936rem;
      justify-content: center;
      align-items: center;

    }

    .go-pay {
      display: flex;

      .par-one {
        border: 0;
        color: #fff;
        padding: .2834rem 1rem;
        border-top-left-radius: 1.4172rem;
        border-bottom-left-radius: 1.4172rem;
        background: linear-gradient(to right, #ff9f69, #ff5b00);
      }

      .par-two {
        border: 0;
        color: #fff;
        padding: .2834rem 1rem;
        border-top-right-radius: 1.4172rem;
        border-bottom-right-radius: 1.4172rem;
        background: linear-gradient(to right, #ff1000, #ff5b00);
      }

    }
  }

}

.tui {
  width: 100%;
  height: 400px;
  display: flex;
  flex-wrap: wrap;
  background: white;
  justify-content: space-around;

  #list_item {
    width: 100%;
    height: 160px;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    border-bottom: 1px solid rgb(214, 214, 214);

    #item_img {
      width: 110px;
      height: 110px;
    }

    #item_con {
      width: 80%;
      height: 100%;
      color: rgb(117, 117, 117);
      margin-left: 10px;

      .ctitle {
        width: 100%;
        height: 50px;
      }

      .cnew {
        width: 100%;
        height: 20px;
        color: red;
      }

      .cbtn {
        width: 100%;
        height: 30px;
        margin-top: 10px;
      }

      .cfot {
        width: 100%;
        height: 65px;
        display: flex;
        justify-content: space-between;
        margin-top: 5px;

        .cfot_left {
          width: 35%;
          height: 100%;

          .del {
            height: 10px;
            line-height: 10px;
            text-decoration: line-through;
          }
        }

        .cfot_right {
          width: 65%;
          height: 100%;

          .join {
            width: 90%;
            height: 30px;
            line-height: 30px;
            background: red;
            color: white;
            border-radius: 20px;
            text-align: center;
            font-size: 14px;
          }
        }
      }
    }
  }

}
</style>